package com.mapapp.flutter_mapapp.http;


import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.mapapp.flutter_mapapp.application.Constants;
import com.mapapp.flutter_mapapp.application.MyApplication;
import com.mapapp.flutter_mapapp.http.gson.GsonConverterFactory;
import com.mapapp.flutter_mapapp.http.service.ApiService;
import com.mapapp.flutter_mapapp.util.SharePreferenceUtil;
import com.mapapp.flutter_mapapp.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

public class Api {
    public static void setApiService(ApiService apiService) {
        API_SERVICE = apiService;
    }

    private static ApiService API_SERVICE;


    /**
     * 请求超时时间
     */
    private static final int DEFAULT_TIMEOUT = 60;

    public static ApiService getApiService() {
        if (API_SERVICE == null) {
            API_SERVICE = getRetrofit().create(ApiService.class);
        }
        return API_SERVICE;
    }

    private static Retrofit getRetrofit() {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });
        Gson gson = builder.create();

        return new Retrofit.Builder()
                .client(getHttpClientBuilder())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Url.BASE_URL)
                .build();
    }

    private static OkHttpClient getHttpClientBuilder() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClientBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                HttpUrl.Builder authorizedUrlBuilder = request.url()
                        .newBuilder();
                Request.Builder requestBuilder = request.newBuilder()
                        .method(request.method(), request.body())
                        .url(authorizedUrlBuilder.build());
                String appToken= (String) SharePreferenceUtil.get(MyApplication.getInstance(), Constants.APPTOKEN, "");
//                String appToken="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY2NvdW50IjoiYWRtaW4iLCJ1c2VySWQiOiIxIn0.wKEsH8jFrW7sspE00HuzxiJpkNCzwvaGhNDg_yvWrHs";
                //添加token
                if (StringUtils.isNotEmpty(appToken)) {
                    requestBuilder.addHeader("Authentication", appToken);
                }
                return  chain.proceed(requestBuilder.build());
            }
        });
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                try {
                    String text = URLDecoder.decode(message, "utf-8");
                    Log.i("OKHttp-----", text);
                } catch (Exception e) {
                    Log.i("OKHttp-----", message);
                }
            }

        });

        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);//这里可以选择拦截级别
        httpClientBuilder.addInterceptor(loggingInterceptor);
        return httpClientBuilder.build();
    }



}
